<template>
  <el-dialog :visible.sync="currentVisible"
             append-to-body
             destroy-on-close
             :close-on-click-modal="false"
             :title="$t('custom.dataset.linkedbotbtn')"
             custom-class="linked-bots-dialog"
             width="990px">
    <el-form v-loading="loading"
             class="flex flex-col"
             style="height:500px">
      <el-checkbox v-if="$hasPermission('sys:dataset:linkedbot')"
                   v-model="form.showAllTenant"
                   style="margin-bottom: 10px;">Show All Tenant</el-checkbox>

      <BGrid :columns="columns"
             :allowResizing="true"
             :allowFiltering="true"
             :showColumnMenu="true"
             :allowGrouping="true"
             :allowReordering="true"
             :allowTextWrap="true"
             :allowSorting="true"
             :allowPaging="true"
             :showColumnChooser="true"
             :sortSettings="{
             columns: [
            { field: 'name', direction: 'Ascending' }
          ]
           }"
             :filterSettings="{ type: 'Excel' }"
             :toolbar="['Search', 'ColumnChooser']"
             :dataSource="linkedBots"
             class="h-0"
             ref="b-grid" />
    </el-form>

    <template slot="footer">
      <el-button size="small"
                 @click="onCancel">{{ $t('cancel') }}</el-button>
    </template>
  </el-dialog>
</template>

<script>
import BGrid from '@/components/storybook/b-grid'
import { renderLinkedBotColumns } from './index.schema'
import bus from '@/components/storybook/utilties/bus'
import { deleteBotInfoApi } from '@/api/new'

export default {
  name: 'BLinkedBots',
  components: {
    BGrid
  },
  props: {
    visible: Boolean,
    gadgetId: String,
    dataSourceId: String
  },
  data () {
    return {
      form: {
        showAllTenant: false
      },
      loading: false,
      linkedBots: []
    }
  },

  computed: {
    currentVisible: {
      get () {
        return this.visible
      },
      set (val) {
        this.$emit('update:visible', val)
      }
    },
    columns () {
      return renderLinkedBotColumns(this.form.showAllTenant)
    }
  },
  watch: {
    async 'form.showAllTenant' () {
      try {
        this.loading = true
        await this.getLinkedBots()
      } finally {
        this.loading = false
      }
    }
  },
  beforeCreate () {
    bus.$on('event:view-linked-bot', (data) => {
      this.onView(data)
    })
    bus.$on('event:delete-linked-bot', (data) => {
      this.onDelete(data)
    })
  },
  created () {
    this.init()
  },
  destroyed () {
    bus.$off('event:view-linked-bot')
    bus.$off('event:delete-linked-bot')
  },
  methods: {
    async onView (data) {
      this.$store.commit('RECORDBOTID', data.id)

      this.$router.push({
        path: `bot-${data.id}`,
        query: {
          pageid: 'botdetail',
          botId: data.id,
          name: data.name
        }
      }, () => {
        this.currentVisible = false
      })
    },
    async onDelete (data) {
      try {
        this.loading = true

        let params = {
          id: data.id
        }

        const { data: response } = await deleteBotInfoApi(params)
        if (response.code !== 0) {
          throw response.msg
        }
        this.$message.success(response.msg)
        this.init()
      } catch (error) {
        this.loading = false
        this.$message.error(error)
      } finally {
      }
    },
    async init () {
      try {
        this.loading = true
        const [linkedBots] = await Promise.all([this.getLinkedBots()])

        this.linkedBots = linkedBots
      } catch (error) {
      } finally {
        this.loading = false
      }
    },
    async getLinkedBots () {
      const { getBotByDatasetListApi } = this.$interface.bots
      const params = {
        ...this.form,
        dataSourceId: this.gadgetId || this.dataSourceId
      }
      const { data: response } = await getBotByDatasetListApi(params)
      if (response.code !== 0) {
        throw response.msg
      }
      return response.data || []
    },
    onCancel () {
      this.currentVisible = false
    }

  }
}
</script>
